#include "DbConnector.h"

DbConnector::DbConnector(QObject *parent)
    : QObject{parent}
{
    // 创建一个数据库连接
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("PiliPiliBuy.db"); // 设置数据库名

    // 打开数据库
    if (!db.open())
    {
        qDebug() << "无法打开数据库:" << db.lastError().text();
    }
    else
    {
        qDebug() << "成功打开数据库";
    }

    // 创建表
    QSqlQuery query;
    QString sql;
    sql = "CREATE TABLE IF NOT EXISTS Messages ("
          "message_id BIGINT AUTO_INCREMENT PRIMARY KEY,"
          "sender_id BIGINT NOT NULL,"
          "receiver_id BIGINT NOT NULL,"
          "content TEXT NOT NULL,"
          "send_time DATETIME NOT NULL);";
    if (query.exec(sql))
    {
        qDebug() << "消息表已创建成功";
    }
    else
    {
        qDebug() << "创建消息表错误：" << query.lastError().text();
    }

    // 插入数据
    query.prepare("INSERT INTO person (name, age) VALUES (:name, :age)");
    query.bindValue(":name", "John Doe");
    query.bindValue(":age", 15);
    if (query.exec())
    {
        qDebug() << "数据插入成功";
    }
    else
    {
        qDebug() << "数据插入失败:" << query.lastError().text();
    }

    // 查询数据
    query.exec("SELECT * FROM person");
    while (query.next())
    {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        int age = query.value(2).toInt();
        qDebug() << "ID:" << id << "Name:" << name << "Age:" << age;
    }
    db.close();
}

DbConnector::~DbConnector()
{
    if (db.isOpen())
        db.close();
}